<template>
    <div class="prize-table">
        <ZwSearchForm row-num="4" :option="searchOption" :default-expand="false" @search="search" @reset="reset" />
        <ZwTable
            ref="tableRef"
            class="table-box"
            :option="tableOption"
            :select-all-group="true"
            :row-key="getRowKey"
            :fetch-params="state.searchParams"
            :fetch-api="fetchApi()"
            @select-all="onSelectAll"
            @select="onSelect"
            @dataChange="onDataChange"
            @selection-change="onSelectionChange"
            @select-all-change="onSelectAllChange"
            @selectAllTotal="selectAllTotal">
            <template #headerOperate>
                <el-button v-auth="'IMPORT_VER_CODE'" @click="operateBtn(1)">导入兑奖码核销</el-button>
                <el-button v-auth="'BATCH_VER'" :disabled="disabled()" @click="operateBtn(2)">批量核销</el-button>
                <el-button v-auth="'PEIZE_EXPORT'" :disabled="disabled()" @click="operateBtn(3, $event)"
                    >导出</el-button
                >
            </template>
        </ZwTable>
    </div>
    <UpFile ref="upFile" @submit="submitFile" />
    <HintText ref="hintTextRef" :hint-text="hintText" @submit="submit"></HintText>
</template>

<script setup lang="tsx">
import { ref, reactive, computed } from 'vue';
import { useRoute } from 'vue-router';
// 查询组件
import ZwSearchForm from '@/components/zw/search-form1.0/SearchForm';
// 引入表格组件
import ZwTable from '@/components/zw/table1.0/Table';
// 引入搜索配置项
import { prizeConfig } from './searchConfig';
// 导入兑奖码核销组件
import UpFile from './UpFile.vue';
// 按钮的二次确认弹框提示文案组件
import HintText from './HintText.vue';
// 用户信息组件
import UserInfo from './UserInfo.vue';

import { getSetionId } from '@/utils/utils';
import { deepCopy } from '@/utils/helper';
import { ElMessage } from 'element-plus';
// 接口
import {
    rewardRecord,
    recordExport,
    batchVerifier,
    importCode,
    verifier,
    sendRed
} from '@/api/smartMarketing/drainage/groupFission';
import { ShowTaskMessage } from '@/hooks/TaskMessageHooks';
import { parabolaAnimation } from '@/utils/parabola';

const emit = defineEmits(['refresh']);

const route = useRoute();
// 弹框组件实例
const upFile = ref<any>(null);
// 表格组件实例
const tableRef = ref<any>(null);
// 表格全选
const selectTableTotal = ref(0);
// 表格全选取消
const cancleAllArray = ref([]);
// 表格当前页全选
const currentSelectArr = ref<any>([]);
// 所有的数据
const totalAll = ref([]);
// 二次提示弹框文案ref
const hintTextRef = ref();
// 弹框文案
const hintText = ref('');

const { id } = route.query;
let clickEvent: any = null;

// 查询组件配置项
const searchOption = computed(() => {
    return prizeConfig(id);
});
// 奖品状态
const getPrizeStatus = (type: any) => {
    const text = {
        1: '库存锁定中',
        2: '已领取',
        3: '库存释放',
        4: '库存不足未发放',
        all: '全部'
    };
    return text[type];
};
// 核销状态
const getVerificationStatus = (type: number) => {
    const text = {
        1: '未核销',
        2: '已核销',
        3: '核销中',
        4: '核销失败',
        all: '全部'
    };
    return text[type];
};
// 是否限制
const getIsEffect = (type: number) => {
    const text = {
        1: '有效',
        2: '无效(超时未核销)',
        3: '无效(用户已限制)',
        4: '无效(单一奖励放弃领取该奖品)',
        5: '无效(助力回退不满足中奖条件)',
        all: '全部'
    };
    return text[type];
};
// 表格配置项
const tableOption = reactive([
    {
        type: 'selection',
        width: 55,
        fixed: 'left',
        reserveSelection: true
    },
    {
        prop: 'activity_name',
        label: '序号',
        width: 55,
        render({ index }: unknown) {
            return <div>{index + 1}</div>;
        }
    },
    {
        prop: 'avatar',
        label: '中奖人',
        width: 180,
        render({ row }: unknown) {
            return <UserInfo name={row.nickname} avatar={row.headimgurl}></UserInfo>;
        }
    },
    {
        prop: 'step_name',
        label: '奖品等级',
        width: 100
    },
    {
        prop: 'avatar',
        label: '奖品信息',
        width: 260,
        render({ row }: unknown) {
            return (
                <div class="prize-info">
                    <UserInfo name={row.reward_title} avatarShape={'square'} avatar={row.reward_image}></UserInfo>
                    <span vShow={row.reward_tip !== ''}>（{row.reward_tip}）</span>
                </div>
            );
        }
    },
    {
        prop: 'created_at',
        label: '达成时间',
        width: 180,
        render({ row }: unknown) {
            return <div>{row.created_at || '--'}</div>;
        }
    },
    {
        prop: 'reward_status',
        label: '奖品状态',
        width: 180,
        render({ row }: unknown) {
            return <div>{getPrizeStatus(row.reward_status)}</div>;
        }
    },
    {
        prop: 'verification_status',
        label: '核销状态',
        width: 180,
        render({ row }: unknown) {
            return <div>{getVerificationStatus(row.verification_status)}</div>;
        }
    },
    {
        prop: 'is_effect',
        label: '是否有效',
        width: 220,
        render({ row }: unknown) {
            return <div>{getIsEffect(row.is_effect)}</div>;
        }
    },
    {
        prop: 'avatar',
        label: '邮寄信息',
        width: 260,
        render({ row }: unknown) {
            const resText = `${row.consignee_name}-${row.consignee_phone}-${row.consignee_address}`;
            return (
                <>
                    <div vShow={row.verification_status === 2}>
                        <UserInfo name={resText} limit={50}></UserInfo>
                    </div>
                    <div vShow={row.verification_status !== 2}>--</div>
                </>
            );
        }
    },
    {
        prop: 'amount',
        label: '红包金额（元）',
        width: 130,
        render({ row }: unknown) {
            return <div>{row.reward_type === 2 ? row.amount : '--'}</div>;
        }
    },
    // 本期暂时隐藏，产品说下期再展示，别删除
    // {
    //     prop: 'verification_remark',
    //     label: '核销备注',
    //     width: 120,
    //     showOverflowTooltip: true,
    //     render({ row }) {
    //         return (
    //             <div class="remark-box">
    //                 <div vShow={row.verification_remark}>
    //                     <ElTooltip placement="top" content={row.verification_remark}>
    //                         <p class="user-name">{row.verification_remark}</p>
    //                     </ElTooltip>
    //                 </div>
    //                 <span vShow={!row.verification_remark}>--</span>
    //             </div>
    //         );
    //     }
    // },
    {
        prop: 'operate',
        label: '操作',
        width: 100,
        fixed: 'right',
        isOperate: true,
        option: [
            {
                name: '核销',
                authCode: 'PRIZE_VER',
                isRender: ({ row }: any) => row.reward_type === 1 && row.is_verf,
                click: (row: any) => operate(row, 1)
            },
            {
                name: '发放红包',
                authCode: 'SEND_RED',
                isRender: ({ row }: any) => row.reward_type == 2 && row.is_send,
                click: (row: any) => operate(row, 2)
            }
        ]
    }
]);
const getRowKey = (row: any) => {
    return row.id;
};
// 表格参数
const defaultParams = reactive({
    id,
    name: '',
    reward_level: 'all',
    reward_status: 'all',
    verification_status: 'all',
    is_effect: 'all'
});
const state = reactive({
    searchParams: deepCopy(defaultParams)
});

const fetchApi = () => {
    return rewardRecord;
};
// 查询参数
const search = (v: any) => {
    tableRef.value.clearAllSelect();
    tableRef.value.clearSelection();
    state.searchParams = deepCopy({ id, ...v });
};
// 重置查询条件
const reset = (v: any) => {
    tableRef.value.clearSelection();
    tableRef.value.clearAllSelect();
    state.searchParams = deepCopy({ id, ...v });
};
// 表格当前页全选
const onSelectAll = (v: any) => {
    currentSelectArr.value = getSetionId('id', v);
};
// 选择表格数据
const onSelect = (v: any) => {
    currentSelectArr.value = getSetionId('id', v);
};
// 改变选项
const onDataChange = (v: any) => {
    totalAll.value = v.total;
};
// 全选的改变
const onSelectAllChange = (v: any) => {
    cancleAllArray.value = v;
};
// 选项的变更
const onSelectionChange = (v: any) => {
    currentSelectArr.value = getSetionId('id', v);
};
// 选中表格所有数据
const selectAllTotal = (v: any) => {
    selectTableTotal.value = v;
};
// 是否禁用批量操作
const disabled = () => {
    if (currentSelectArr.value.length > 0 || selectTableTotal.value > 0) {
        return false;
    } else {
        return true;
    }
};
// 操作按钮
const operate = (row: any, type: number) => {
    switch (type) {
        case 1:
            hintText.value = `确定要核销该条奖品吗？`;
            hintTextRef.value.open(hintText.value, row, 2);
            break;
        case 2:
            hintText.value = `确定要发放该活动红包吗？`;
            hintTextRef.value.open(hintText.value, row, 3);
            break;
    }
};
// 操作按钮的公共参数
const publicParams = () => {
    let params = {
        ...state.searchParams,
        select_type: 1,
        contain_ids: currentSelectArr.value
    };
    if (tableRef.value.getIsSelectAll()) {
        params = {
            exclude_ids: cancleAllArray.value,
            ...state.searchParams,
            select_type: 2
        };
    }
    return params;
};
// 导出数据
const exportData = () => {
    recordExport(publicParams())
        .then(() => {
            parabolaAnimation(clickEvent);
            ShowTaskMessage('导出异步任务创建成功');
            tableRef.value.clearSelection();
            tableRef.value.clearAllSelect();
        })
        .catch((error: any) => {
            ElMessage.error(error);
        });
};
// 批量操作按钮，1——导入核销，2——批量核销，3——导出
const operateBtn = (num: number, e?: any) => {
    clickEvent = e;
    switch (num) {
        case 1:
            upFile.value.open();
            break;
        case 2:
            hintText.value = `确定要批量核销选中的${selectTableTotal.value}条数据吗？`;
            hintTextRef.value.open(hintText.value, '', 1);
            break;
        case 3:
            exportData();
            break;
    }
};
// 文案弹框的二次确认
const submit = (row: any, type: number, e: any) => {
    switch (type) {
        case 1:
            batchVerifier(publicParams())
                .then(() => {
                    parabolaAnimation(e);
                    ShowTaskMessage('核销异步任务创建成功');
                    tableRef.value.clearSelection();
                    tableRef.value.clearAllSelect();
                    emit('refresh');
                    tableRef.value.reload();
                })
                .catch((error: any) => {
                    ElMessage.error(error);
                });
            break;
        case 2:
            verifier({ id, record_id: row.id })
                .then(() => {
                    ElMessage.success('核销成功');
                    emit('refresh');
                    tableRef.value.reload();
                })
                .catch((error: any) => {
                    ElMessage.error(error);
                });
            break;
        case 3:
            sendRed({ id, external_userid: row.external_userid, record_id: row.id })
                .then(() => {
                    emit('refresh');
                    ElMessage.success('发放红包成功');
                })
                .catch((error: any) => {
                    ElMessage.error(error);
                });
            break;
    }
};
// 导入核销码
const submitFile = (data: any, e: any) => {
    importCode({ id, code: data.code })
        .then(() => {
            parabolaAnimation(e);
            ShowTaskMessage('导入核销异步任务创建成功');
        })
        .catch((error: any) => {
            ElMessage.error(error);
        });
};
</script>

<style lang="scss" scoped>
.prize-table {
    :deep(.prize-info) {
        display: flex;
        align-content: center;
        flex-wrap: nowrap;

        .user-name {
            font-weight: 400;
            max-width: 100px;
            margin-left: 8px;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
        }
    }

    :deep(.remark-box) {
        max-width: 120px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
    }
}
</style>
